--[[
@classmod Tile
]]

local lume = require('lib.lume')

return Class {
	_name = "Tile", 
	init = function (self, x, y)
		self.x = x or 0
		self.y = y or 0
		self.s = 8
		return self
	end,
	
	get_position = function (self)
		return self.x, self.y
	end,
	
	is_equal = function (self, tile)
		if not tile or not tile.is_a then return false end
		if tile.x == self.x and tile.y == self.y then
			return true
		end
		return false
	end,
	
	select = function (self)
		if self:is_equal(Game.current_tile) then return end
		if self.x < 0 or self.y < 0 or self.x > 512-8 or self.y > 512-8 then return end
		Game.cursor.grid:highlight(self.x, self.y)
		Game.current_tile = self
		return self
	end,
	
	clear = function (self, layer)
		local layer = Game.current_layer
		layer.cvs:renderTo(function ()
			local x, y = self.x, self.y
			_lg.setScissor( x, y, self.s, self.s)
			_lg.clear()
			_lg.setScissor()
		end)
	end,
	
	focus = function (self)
		Game.current_layer:focus_on(self.x, self.y, self.s, self.s)
		self:copy ()
	end,
	
	copy = function (self)
		Game.tile_buffer = self:get_img_data()
		Game.gui.tile_display_widget:redraw()
	end,
	
	paste = function (self, data ,layer)
		local layer = Game.current_layer
		local data = Game.tile_buffer
		if not data then return end
		self:clear()
		layer.cvs:renderTo(function ()
			local x, y = self.x, self.y
			local img = _lg.newImage(data)
			_lg.draw(img, x, y)
		end)
	end,
	
	flip = function (self, dir)
		local sx, sy = 1, 1
		local nx, ny = self.x, self.y
		local s = self.s
		if dir == "h" then
			sx = -1
			nx = nx + s
		elseif dir == "v" then
			sy = -1
			ny = ny + s
		end
		self:clear()
		local layer = Game.current_layer
		local data = Game.tile_buffer
		layer.cvs:renderTo(function ()
			local x, y = self.x, self.y
			local img = _lg.newImage(data)
			_lg.draw(img, nx, ny, nil, sx, sy)
		end)
		Game.tile_buffer = self:get_img_data ()
	end,
	
	get_img_data = function (self)
		if not Game.current_layer then return end
		return Game.current_layer.cvs:newImageData(nil, nil, self.x, self.y, self.s, self.s)
	end,
	
	set_img_data = function (self, img_data)
		if not Game.current_layer then return end
		local img_data = img_data or TileBuff
		self:paste(img_data)
	end,
	
	export = function (self, filename)
		local data = self:get_img_data ()
		data:encode("png", "tiles/" .. filename..".png")
	end,
	
	save = function (self)
	
	end,
}
